package cn.aifeix.pet.service.impl;

import cn.aifeix.pet.domain.PetType;
import cn.aifeix.pet.mapper.PetTypeMapper;
import cn.aifeix.pet.service.IPetTypeService;
import cn.aifeix.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aifeix
 * @since 2022-10-28
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> petTypeTree() {
        List<PetType> result = new ArrayList<>();
        List<PetType> allPetTypes = petTypeMapper.findAll();
        if (CollectionUtils.isEmpty(allPetTypes)){
            return result;
        }

        // stream流转为map
        Map<Long, PetType> parentMap = allPetTypes.stream().collect(Collectors.toMap(PetType::getId, e -> e));

        // 遍历
        for (PetType petType : allPetTypes) {
            if (null == petType.getPid()) {
                // 它就是最大的那个
                result.add(petType);
            } else {
                // 当前的这个petType 是个儿子
                // 找爹 自己是个儿子 有爹的id
                PetType parent = parentMap.get(petType.getPid());
                if (null == parent){
                    break;
                }
                List<PetType> children = parent.getChildren();
                children.add(petType);
            }
        }
        return result;
    }
}
